package logic

import (
	"context"
	"time"

	"mall/common/enumx"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RemoveUserTransactionLogLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRemoveUserTransactionLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RemoveUserTransactionLogLogic {
	return &RemoveUserTransactionLogLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RemoveUserTransactionLogLogic) RemoveUserTransactionLog(in *user.RemoveUserTransactionLogRequest) (*user.RemoveUserTransactionLogResponse, error) {
	if len(in.Ids) == 0 && in.SourceId == 0 {
		return &user.RemoveUserTransactionLogResponse{}, nil
	}

	now := time.Now() // 本地时间
	if len(in.Ids) > 0 {
		filterMap := make(map[string]map[string][]interface{})
		ids := make([]interface{}, 0, len(in.Ids))
		for _, id := range in.Ids {
			ids = append(ids, uint64(id))
		}
		filterMap[model.UserTransactionLogColumns.UserTransactionLogID] = map[string][]interface{}{
			"in": ids,
		}
		filterMap[model.UserTransactionLogColumns.UserID] = map[string][]interface{}{
			"equalTo": []interface{}{in.UpdatedBy},
		}
		_, err := l.svcCtx.User.UpdateTransactionLogBatch(l.ctx, model.M{
			model.UserTransactionLogColumns.Status:    uint8(enumx.ObjectStatusDeleted),
			model.UserTransactionLogColumns.UpdatedAt: now,
		}, filterMap)
		if err != nil {
			return nil, err
		}
	} else if in.SourceId > 0 {
		filterMap := make(map[string]map[string][]interface{})
		filterMap[model.UserTransactionLogColumns.SourceID] = map[string][]interface{}{
			"equalTo": []interface{}{in.SourceId},
		}
		filterMap[model.UserTransactionLogColumns.UserID] = map[string][]interface{}{
			"equalTo": []interface{}{in.UserId},
		}
		_, err := l.svcCtx.User.UpdateTransactionLogBatch(l.ctx, model.M{
			model.UserTransactionLogColumns.Status:    uint8(in.Status),
			model.UserTransactionLogColumns.UpdatedAt: now,
		}, filterMap)
		if err != nil {
			return nil, err
		}
	}

	return &user.RemoveUserTransactionLogResponse{}, nil
}
